package com.crpc.runner;

import cn.hutool.core.util.ObjectUtil;
import com.crpc.common.annotation.CrpcAPi;
import com.crpc.config.CrpcProperties;
import com.crpc.config.RegisterProperties;
import com.crpc.core.CrpcBootStrap;
import com.crpc.core.ServiceConfig;
import com.crpc.core.compress.CompressorFactory;
import com.crpc.core.compress.CompressorWrapper;
import com.crpc.core.discovery.RegistryConfig;
import com.crpc.core.loadBalance.LoadBalanceFactory;
import com.crpc.core.loadBalance.LoadBalanceWrapper;
import com.crpc.core.serialize.SerializerFactory;
import com.crpc.core.serialize.SerializerWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.crpc.core.CrpcBootStrap.SPRINGBOOt_SERVICE_Configs;

@Slf4j
@Component
public class CrpcBootstrapPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        CrpcAPi annotation = bean.getClass().getAnnotation(CrpcAPi.class);
        if (ObjectUtil.isNull(annotation)) {
            return bean;
        }
        Object instance = null;
        try {
            instance = bean.getClass().getConstructor().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        Class<?>[] interfaces = bean.getClass().getInterfaces();
        for (Class<?> interfaceClazz : interfaces) {
            ServiceConfig<Object> serviceConfig = new ServiceConfig<>();
            serviceConfig.setInterfaceProvider((Class) interfaceClazz);
            serviceConfig.setRefImpl(instance);
            SPRINGBOOt_SERVICE_Configs.add(serviceConfig);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
